package com.da.common.utils;

import cn.hutool.core.util.DesensitizedUtil;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-01-13
 * @Version: 1.0
 */

public class PhoneUtils {

    /**
     * 将手机号中间几位替换为星号
     * @param phone 手机号
     * @return 脱敏后的手机号
     */
    public static String maskPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return phone; // 如果不是有效的手机号，则不进行处理
        }

        return DesensitizedUtil.mobilePhone(phone);
    }



    // 密钥生成
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // 可以选择128, 192, 256位
        return keyGenerator.generateKey();
    }


    // 加密手机号
    public static String encrypt(String phoneNumber, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(phoneNumber.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密手机号
    public static String decrypt(String encryptedPhoneNumber, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedPhoneNumber);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }



}
